import { isHybrid, saveImage } from './h5/hybrid';
/**
 * 设置标题
 */
// TODO 分到@doctorwork/utils里？
export const setNavigationBarTitle = title => {
    wx.setNavigationBarTitle({
        title
    });
};

/**
 * 登录小程序
 */
export const loginWexin = function() {
    return new Promise(async resolve => {
        wx.login({
            success: async function({ code }) {
                if (code) {
                    resolve(code);
                }
            }
        });
    });
};


/**
 * 获取
 */
export const getSetting = function() {
    return new Promise(function(resolve, reject) {
        wx.getSetting({
            success(res) {
                if (res.authSetting) {
                    resolve(res.authSetting);
                } else {
                    resolve(res);
                }
            }
        });
    });
};

/**
 * 保存图片到本地
 * @param {*} url
 */
export const saveImageToPhotos = function(url) {
    if (isHybrid) {
        saveImage(url);
        return;
    }
    return new Promise(function(resolve) {
        wx.downloadFile({
            url: url,
            success: function(res) {
                //图片保存到本地
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: function(data) {
                        wx.showToast({
                            title: '保存成功',
                            icon: 'success',
                            duration: 3000
                        });
                    },
                    fail: function(err) {
                        if (
                            err.errMsg ===
                            'saveImageToPhotosAlbum:fail auth deny'
                        ) {
                            console.log('当初用户拒绝，再次发起授权');
                            wx.openSetting({
                                success(settingdata) {
                                    if (
                                        settingdata.authSetting[
                                            'scope.writePhotosAlbum'
                                        ]
                                    ) {
                                        console.log(
                                            '获取权限成功，给出再次点击图片保存到相册的提示。'
                                        );
                                    } else {
                                        console.log(
                                            '获取权限失败，给出不给权限就无法正常使用的提示'
                                        );
                                    }
                                }
                            });
                        }
                    },
                    complete(res) {
                        console.log(res);
                    }
                });
            }
        });
    });
};

/**
 * 小程序扫码转码函数
 * @param {*} url
 */
export const parseQueryString = url => {
    if (/\?/.test(url)) {
        let searchParams = url.split('?')[1];
        let searchJsonStr = searchParams.replace(/&|=/g, m => {
            if (m === '&') {
                return '", "';
            } else if (m === '=') {
                return '": "';
            }
        });
        return searchJsonStr ? JSON.parse(`{"${searchJsonStr}"}`) : {};
    } else {
        return {};
    }
};

/**
 * @deprecation
 * @FIXME: 和 $app model 重复，组件启用
 * 判断设备型号
 * 例如iphone 则返回iphonex
 */
export const getDeviceInfo = () => {
    const device = {};

    try {
        var res = wx.getSystemInfoSync();
        Object.keys(res).forEach(item => {
            device[item] = res[item];
        });
    } catch (e) {
        // Do something when catch error
    }

    device.iPhoneX = /iPhone X/.test(device.model);

    return device;
};
